package com.wskj.workbench.component;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wskj.common.constant.Constants;
import com.wskj.common.core.domain.entity.SysUser;
import com.wskj.common.core.domain.entity.TbUserTiktok;
import com.wskj.common.utils.common.ServletUtils;
import com.wskj.common.utils.ip.AddressUtils;
import com.wskj.system.domain.SysLogininfor;
import com.wskj.system.domain.SysOperLog;
import com.wskj.system.service.ISysConfigService;
import com.wskj.system.service.ISysLogininforService;
import com.wskj.system.service.ISysOperLogService;
import com.wskj.system.service.ISysUserService;
import com.wskj.workbench.domain.TbTiktokOrder;
import com.wskj.workbench.domain.TbUserWalletDetail;
import com.wskj.workbench.enums.UserTypeEnum;
import com.wskj.workbench.enums.UserWalletDetailRecommendTypeEnum;
import com.wskj.workbench.service.ITbTiktokOrderService;
import com.wskj.workbench.service.ITbUserTiktokService;
import com.wskj.workbench.service.ITbUserWalletDetailService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 异步工厂（产生任务用）
 *
 * @author Lion Li
 */
@Slf4j(topic = "sys-user")
@Async
@Component
@AllArgsConstructor(onConstructor_ = {@Lazy})
public class AsyncService {


    private final ISysLogininforService iSysLogininforService;

    private final ISysOperLogService iSysOperLogService;

    private final ITbTiktokOrderService tbTiktokOrderService;

    private final ITbUserTiktokService tbUserTiktokService;

    private final ISysUserService sysUserService;

    private final ITbUserWalletDetailService tbUserWalletDetailService;

    private final ISysConfigService sysConfigService;

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     */
    public void recordLogininfor(final String username, final String status, final String message,
                                 HttpServletRequest request, final Object... args) {
        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        final String ip = ServletUtils.getClientIP(request);

        String address = AddressUtils.getRealAddressByIp(ip);
        StringBuilder s = new StringBuilder();
        s.append(getBlock(ip));
        s.append(address);
        s.append(getBlock(username));
        s.append(getBlock(status));
        s.append(getBlock(message));
        // 打印信息到日志
        log.info(s.toString(), args);
        // 获取客户端操作系统
        String os = userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        // 封装对象
        SysLogininfor logininfor = new SysLogininfor();
        logininfor.setUserName(username);
        logininfor.setIpaddr(ip);
        logininfor.setLoginLocation(address);
        logininfor.setBrowser(browser);
        logininfor.setOs(os);
        logininfor.setMsg(message);
        // 日志状态
        if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
            logininfor.setStatus(Constants.SUCCESS);
        } else if (Constants.LOGIN_FAIL.equals(status)) {
            logininfor.setStatus(Constants.FAIL);
        }
        // 插入数据
        iSysLogininforService.insertLogininfor(logininfor);
    }

    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     */
    public void recordOper(final SysOperLog operLog) {
        // 远程查询操作地点
        operLog.setOperLocation(AddressUtils.getRealAddressByIp(operLog.getOperIp()));
        iSysOperLogService.insertOperlog(operLog);
    }

    private String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg + "]";
    }


    public void handleCommission(List<TbTiktokOrder> list) {

        // 如果总金额为0  或者 判断分账单id+佣金类型已经存在   或者  判断抖音号不存在 或者内容类型为空的
        // 如果这4个条件有一个满足 就过滤掉
        List<TbTiktokOrder> saveList = list.stream().filter(itm -> itm.getTotalPrice().compareTo(BigDecimal.ZERO) > 0
                && tbTiktokOrderService.count(Wrappers.lambdaQuery(TbTiktokOrder.class).eq(TbTiktokOrder::getBillId, itm.getBillId())
                .eq(TbTiktokOrder::getCommissionType,itm.getCommissionType())) == 0
                && tbUserTiktokService.count(Wrappers.lambdaQuery(TbUserTiktok.class).eq(TbUserTiktok::getTikUid, itm.getTiktokUid())) != 0
                && ObjectUtil.isNotEmpty(itm.getContentType())
                && (itm.getContentType().equals("1") || (itm.getContentType().equals("2")))
        ).collect(Collectors.toList());
        tbTiktokOrderService.saveBatch(saveList);
        List<TbTiktokOrder> all = tbTiktokOrderService.list(Wrappers.lambdaQuery(TbTiktokOrder.class).eq(TbTiktokOrder::getSfSettlement, "1"));
        for (TbTiktokOrder tbTiktokOrder : all) {
            handleOrder(tbTiktokOrder);
        }
    }


    private void handleOrder(TbTiktokOrder tbTiktokOrder) {
        // 默认没有结算过
        tbTiktokOrder.setSfSettlement("2");
        tbTiktokOrderService.updateById(tbTiktokOrder);

        // 查询抖音
        TbUserTiktok tbUserTiktok = tbUserTiktokService.getOne(Wrappers.lambdaQuery(TbUserTiktok.class)
                .eq(TbUserTiktok::getTikUid, tbTiktokOrder.getTiktokUid()));

        // 查询抖音uid对应的用户
        Long userId = tbUserTiktok.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);


        BigDecimal totalAdd = sysUser.getTotalAmount().add(tbTiktokOrder.getTotalPrice());
        BigDecimal tiktokAdd = sysUser.getTiktokAmount().add(tbTiktokOrder.getTotalPrice());
        sysUser.setTotalAmount(totalAdd);
        sysUser.setTiktokAmount(tiktokAdd);
        sysUserService.updateById(sysUser);


        // 记录用户收入明细
        TbUserWalletDetail tbUserWalletDetail = new TbUserWalletDetail();
        tbUserWalletDetail.setUserId(userId);
        tbUserWalletDetail.setTikUid(tbTiktokOrder.getTiktokUid());
        tbUserWalletDetail.setPhoneNumber(sysUser.getPhoneNumber());
        tbUserWalletDetail.setRealName(sysUser.getRealName());
        tbUserWalletDetail.setDetailType(tbTiktokOrder.getContentType());
        tbUserWalletDetail.setDetailPrice(tbTiktokOrder.getTotalPrice());
        tbUserWalletDetailService.save(tbUserWalletDetail);

        //  给上级和上上级分佣
        handleComm(sysUser, tbTiktokOrder);

    }

    private void handleComm(SysUser rooUser, TbTiktokOrder tiktokOrder) {
        // 直属上级
        SysUser zhiUser = sysUserService.getById(rooUser.getZhiUserId());

        if (ObjectUtil.isEmpty(zhiUser)) {
            return;
        }


        String userType = zhiUser.getUserType();
        // 如果上级是主播 则只有佣金提成 没有招商提成
        if (userType.equals(UserTypeEnum.ZHUBO.getValue())) {
            String zhituiPercent = sysConfigService.selectConfigByKey("zhitui_percent");


            // 直接上级提成
            BigDecimal zhijiticheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(zhituiPercent)).divide(new BigDecimal(100))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);

            zhiUser.setTotalAmount(zhiUser.getTotalAmount().add(zhijiticheng));
            zhiUser.setPromoAmount(zhiUser.getPromoAmount().add(zhijiticheng));
            sysUserService.updateById(zhiUser);

            // 钱包明细增加
            handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.ZHITUI.getValue(), zhiUser, tiktokOrder, zhijiticheng);


            // 查询上上级
            SysUser parentUser = sysUserService.getById(zhiUser.getZhiUserId());
            if (ObjectUtil.isNotEmpty(parentUser)) {

                if (parentUser.getUserType().equals(UserTypeEnum.ZHUBO.getValue())) {

                    // 间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("jiantui_percent");

                    // 间接上级提成
                    BigDecimal shangjitiacheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tiktokOrder, shangjitiacheng);


                } else if (parentUser.getUserType().equals(UserTypeEnum.TUANZHANG.getValue())) {

                    // 间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("tzyjjt_percert");

                    // 间接上级提成
                    BigDecimal shangjitiacheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tiktokOrder, shangjitiacheng);

                }else if (parentUser.getUserType().equals(UserTypeEnum.FENGONGSI.getValue())) {

                    // 间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("fengonsgIyongjanbi");

                    // 间接上级提成
                    BigDecimal shangjitiacheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tiktokOrder, shangjitiacheng);

                }
            }


        } else if (userType.equals(UserTypeEnum.TUANZHANG.getValue())) {
            // 如果是团长
            String tuanzhangZhituiPercent = sysConfigService.selectConfigByKey("tzyjztbl_percert");


            // 直接上级提成
            BigDecimal zhijiticheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(tuanzhangZhituiPercent)).divide(new BigDecimal(100))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);

            zhiUser.setTotalAmount(zhiUser.getTotalAmount().add(zhijiticheng));
            zhiUser.setPromoAmount(zhiUser.getPromoAmount().add(zhijiticheng));
            sysUserService.updateById(zhiUser);

            // 钱包明细增加
            handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.ZHITUI.getValue(), zhiUser, tiktokOrder, zhijiticheng);


            // 查询上上级
            SysUser parentUser = sysUserService.getById(zhiUser.getZhiUserId());
            if (ObjectUtil.isNotEmpty(parentUser)) {


                if (parentUser.getUserType().equals(UserTypeEnum.ZHUBO.getValue())) {

                    // 间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("jiantui_percent");

                    // 间接上级提成
                    BigDecimal shangjitiacheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tiktokOrder, shangjitiacheng);


                } else if (parentUser.getUserType().equals(UserTypeEnum.TUANZHANG.getValue())) {

                    // 间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("tzyjjt_percert");

                    // 间接上级提成
                    BigDecimal shangjitiacheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tiktokOrder, shangjitiacheng);

                }else if (parentUser.getUserType().equals(UserTypeEnum.FENGONGSI.getValue())) {

                    // 间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("fengonsgIyongjanbi");

                    // 间接上级提成
                    BigDecimal shangjitiacheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tiktokOrder, shangjitiacheng);

                }

            }

        } else if (userType.equals(UserTypeEnum.FENGONGSI.getValue())) {

            // 如果是分公司
            String fengongsiZhituiPercent = sysConfigService.selectConfigByKey("fengosngsizhituibil");


            // 直接上级提成
            BigDecimal zhijiticheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(fengongsiZhituiPercent)).divide(new BigDecimal(100))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);

            zhiUser.setTotalAmount(zhiUser.getTotalAmount().add(zhijiticheng));
            zhiUser.setPromoAmount(zhiUser.getPromoAmount().add(zhijiticheng));
            sysUserService.updateById(zhiUser);

            // 钱包明细增加
            handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.ZHITUI.getValue(), zhiUser, tiktokOrder, zhijiticheng);


            // 查询上上级
            SysUser parentUser = sysUserService.getById(zhiUser.getZhiUserId());
            if (ObjectUtil.isNotEmpty(parentUser)) {


                if (parentUser.getUserType().equals(UserTypeEnum.ZHUBO.getValue())) {

                    // 间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("jiantui_percent");

                    // 间接上级提成
                    BigDecimal shangjitiacheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tiktokOrder, shangjitiacheng);


                } else if (parentUser.getUserType().equals(UserTypeEnum.TUANZHANG.getValue())) {

                    // 间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("tzyjjt_percert");

                    // 间接上级提成
                    BigDecimal shangjitiacheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tiktokOrder, shangjitiacheng);

                }else if (parentUser.getUserType().equals(UserTypeEnum.FENGONGSI.getValue())) {

                    // 间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("fengonsgIyongjanbi");

                    // 间接上级提成
                    BigDecimal shangjitiacheng = tiktokOrder.getTotalPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(rooUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tiktokOrder, shangjitiacheng);

                }

            }


        }
    }

    private void handleWallet(SysUser rootUser, String recommendType, SysUser sysUser, TbTiktokOrder tbTiktokOrder, BigDecimal price) {
        if (price.compareTo(BigDecimal.ZERO) > 0) {


            TbUserWalletDetail tbUserWalletDetail = new TbUserWalletDetail();
            tbUserWalletDetail.setUserId(sysUser.getUserId());
            tbUserWalletDetail.setTikUid(tbTiktokOrder.getTiktokUid());
            tbUserWalletDetail.setPhoneNumber(sysUser.getPhoneNumber());
            tbUserWalletDetail.setRealName(sysUser.getRealName());

            tbUserWalletDetail.setDetailType(tbTiktokOrder.getContentType());
            tbUserWalletDetail.setDetailPrice(price);

            // 贡献人信息
            tbUserWalletDetail.setRecommendType(recommendType);
            if (ObjectUtil.isNotEmpty(rootUser)) {
                tbUserWalletDetail.setRecommendId(rootUser.getUserId());
                tbUserWalletDetail.setRecommendName(rootUser.getRealName());
                tbUserWalletDetail.setRecommendPhone(rootUser.getPhoneNumber());
                tbUserWalletDetail.setRecommendAvatar(rootUser.getAvatar());
            }
            tbUserWalletDetailService.save(tbUserWalletDetail);
        }


    }
}
